package top.scauwlt.compress.gzip;

import lombok.extern.slf4j.Slf4j;
import org.apache.curator.framework.imps.GzipCompressionProvider;
import top.scauwlt.compress.Compress;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;

/**
 * @Author wmm
 * @Date 2022/7/23 20:20
 */
@Slf4j
public class GzipCompress implements Compress {

    private static final int BUFFER_SIZE = 1024 * 4;

    @Override
    public byte[] compress(byte[] bytes) {
        if (bytes == null) {
            throw new IllegalArgumentException("gzip compress bytes should not be null!");
        }
        try (ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
             GZIPOutputStream gzipOutputStream = new GZIPOutputStream(outputStream)) {
            gzipOutputStream.write(bytes);
            gzipOutputStream.flush();
            gzipOutputStream.finish();
            return outputStream.toByteArray();
        } catch (IOException e) {
            log.error("gzip compress failed: {}", e.getMessage());
            throw new RuntimeException("gzip compress failed");
        }
    }

    @Override
    public byte[] decompress(byte[] bytes) {
        if (bytes == null) {
            throw new IllegalArgumentException("gzip decompress bytes should not be null!");
        }
        try (ByteArrayOutputStream out = new ByteArrayOutputStream();
             ByteArrayInputStream input = new ByteArrayInputStream(bytes);
             GZIPInputStream gzipInputStream = new GZIPInputStream(input)) {
            byte[] buffer = new byte[BUFFER_SIZE];
            int n;
            while ((n = gzipInputStream.read(buffer)) > -1) {
                out.write(buffer, 0, n);
            }
            return out.toByteArray();
        } catch (IOException e) {
            throw new RuntimeException("gzip decompress bytes failed");
        }
    }
}
